<template>
  <div class="container" v-loading="isLoading">
    <el-card>
      <template #header>
        <el-form inline ref="searchForm">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="searchForm.real_name"
              placeholder="请输入用户名称"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input
              v-model="searchForm.phone"
              placeholder="请输入手机号码"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="小区名称" prop="communityid">
            <el-select v-model="searchForm.subdistrict_id">
              <el-option label="全部" value=""/>
              <el-option
                v-for="(oVal, oIdx) of communityList"
                :key="oIdx"
                v-bind="oVal"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList">查询</el-button>
          </el-form-item>
        </el-form>
        <div class="table_tool">
          <el-button type="success" @click="exportExcel">导出报名报表</el-button>
        </div>
        <!-- <div class="table_tool">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="showAddOrEdit = true"
            >新增</el-button
          >
        </div> -->
      </template>

      <el-table :data="tableData" border id="out-table" stripe>
        <el-table-column prop="real_name" label="用户姓名" />
        <el-table-column prop="nick_name" label="微信昵称" />
        <el-table-column prop="phone" label="用户手机号" />
        <el-table-column prop="identity_num" label="用户身份证号" />
        <el-table-column prop="sex" label="性别">
          <template slot-scope="{ row }">
            {{ row.sex==1?'男':'女' }}
          </template>
        </el-table-column>

        <el-table-column prop="subdistrict_id" label="所属小区">
          <template #default="{row}">
            {{communityTexts[row.subdistrict_id-1]}}
          </template>
        </el-table-column>
        <el-table-column prop="global_balance" label="用户积分" />
        <el-table-column prop="avatar_url" label="头像" align="center">
          <template slot-scope="{ row }">
            <el-image v-if="row.avatar_url"
              style="width: 100px; height: 100px"
              :src="row.avatar_url"
              :preview-src-list="[row.avatar_url]"
              />
            <div v-else>暂未上传</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px" align="center">
          <template slot-scope="{ row }">
            <el-button
              type="text"
              @click="editScore(row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <footer class="footer">
      <el-pagination
        background
        layout="total, sizes, pager, jumper"
        :current-page="searchForm.page"
        :page-sizes="[10,20, 30, 50, 100]"
        :page-size="searchForm.page_size"
        :total="tableTotal"
        @size-change="changeSize"
        @current-change="changeCurrent"
      />
    </footer>


    <el-dialog
      title="编辑用户积分"
      :visible.sync="showAddOrEdit"
      width="888px"
      @closed="closeDialog"
    >
      <el-form
        :model="builingForm"
        ref="builingForm"
        label-width="14em"
      >
        <el-form-item prop="$id" hidden />
        <el-form-item label="修改积分（传入负数为减少）" prop="score">
          <el-input v-model="builingForm.score" placeholder="请输入分值" />
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button
          type="primary"
          @click="submitData()"
          :loading="loading.update"
          >确 定</el-button
        >
      </template>
    </el-dialog>

  </div>
</template>

<script>
import API from '@/api';
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
import { table, addOrEdit } from "@/utils/mixins";
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapActions } = createNamespacedHelpers('asyncStatus')
export default {
  mixins: [table, addOrEdit],
  data: () => ({
    showAddOrEdit: false,
    maxScore:"",
    isLoading: true,
    tableData:[],
    tableTotal: 0,
    isKey: false,
    searchForm:{
      status:2,
      real_name:"",
      phone:"",
      subdistrict_id:"",
      page:1,
      per_page:10
    },
    sex:[
      {
        value: 1,
        label: "男",
      },
       {
        value: 2,
        label: "女",
      },
    ],
    communityList: [],
    communityTexts:[],
    builingForm:{
      $id:"",
      score:""
    }

  }),

  created() {
    this.getList()
    API.getCommunityList().then(({data})=>{
      this.communityList=data.items.map(item=>{
        return {value:item.id,label:item.name}
      })
      this.communityTexts=data.items.map(item=>{
        return item.name
      })
    })
  },

  methods: {
    //列表
    getList(){
      API.getHouseholdAuditList(this.searchForm)
        .then(({ data }) => {
          data.items.forEach(item=>{
            item.sex=parseInt(item.sex)
            item.status=parseInt(item.status)
            // item.phone=item.phone.replace(/^(\d{3})\d{4}(\d+)/, '$1****$2')
            // item.identity_num=item.identity_num.replace(/^(.{6})(?:\d+).(.{4})$/,'$1****$2')
          })
          this.tableData = data.items
          this.tableTotal = data.total
        })
        .catch((err) => {
          this.tableData = []
          this.tableTotal=0
        });
    },

    // 分页
    changeSize(val){
      this.searchForm.per_page = val
      this.searchForm.page = 1
      this.getList()
    },

    // 分页
    changeCurrent(val){
      this.searchForm.page = val
      this.getList()
    },

    // 编辑用户积分
    editScore(obj){
      this.maxScore=obj.global_balance
      this.builingForm.$id=obj.id
      this.showAddOrEdit=true
    },

    // 关闭弹窗
    closeDialog(){
      this.showAddOrEdit=false
      this.restForm()
    },

    // 修改积分
    submitData(){
      let num=this.builingForm.score
      if(num<0&&this.maxScore<Math.abs(num)){
        this.$message.error('积分不可为负数');
      }else{
        API.changeScore(this.builingForm.$id,{score:this.builingForm.score}).then(()=>{
          this.$message.success("编辑成功！");
        }).catch(()=>{}).finally(() =>{
          this.restForm()
          this.getList()
          this.showAddOrEdit=false
        })
      }
    },

    // 重置表单
    restForm(){
      this.builingForm.score=0,
      this.builingForm.$id=""
    },


    exportExcel() {
      var wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
            new Blob([wbout], { type: "application/octet-stream" }),
            `人员信息导出数据.xlsx`
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },

  },
};
</script>

<style lang="scss" scoped></style>
